package cn.pzhu.services.web;

import cn.pzhu.model.Achievement;
import cn.pzhu.model.Demand;
import cn.pzhu.model.PageBean;
import cn.pzhu.services.BaseServices;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * Created by dongp on 2016/5/8.
 */
public class WebDemandServices extends BaseServices {

    /**
     * 默认查询前6条数据
     * @return
     */
    public List querySix() {
        List<Demand> demands = Demand.dao.find("select * from issuedemand t1 left join category t2 on t1.categoryID = t2.typeVal limit " + 0 + "," + 6);
        return demands;
    }

    public List queryPage(HttpServletRequest request, String typeVal, String search) {
        // session获取分页参数
        HttpSession session = request.getSession();
        PageBean pageBean = (PageBean) session.getAttribute("pageBean");
        if(pageBean == null) {
            pageBean = new PageBean();
        }
        String page = request.getParameter("page");
        if(page != null && page != "") {
            pageBean.setPageOffset(Integer.parseInt(page));
        }

        List<Demand> demands = Demand.dao.find("select t1.*,t2.typeName,t2.typeVal from issuedemand t1 "+
                "left join category t2 on t1.categoryID=t2.typeVal where t1.categoryID like '%"+typeVal+"%' and t1.name like '%"+
                search+"%' limit "+ (pageBean.getPageOffset()-1)*pageBean.getPageSize()+
                ","+pageBean.getPageSize());

        Demand demand = Demand.dao.findFirst("select count(*) total from issuedemand t1 where " +
                " t1.categoryID like '%"+typeVal+"%' and t1.name like '%"+search+"%'");
        int total = demand.getLong("total").intValue();
        pageBean.setTotal(total);
        session.setAttribute("pageBean", pageBean);
        return demands;
    }

    public Demand queryById(int id){
        Demand demand = Demand.dao.findFirst("select t1.*, t2.* from issuedemand t1 left join category t2 on t1.categoryID = t2.typeVal " +
                "where t1.demandID = ?",id);
        return demand;
    }

    public List queryByUserId(int userId) {
        List<Demand> demands = Demand.dao.find("select t1.*,t2.* from issuedemand t1 left join category t2 on t1.categoryID = t2.typeVal " +
                "where t1.userID = ?",userId);
        return demands;
    }

    public boolean delDemand(int id) {
        boolean result = Demand.dao.deleteById(id);
        return result;
    }

}
